// 文档智能摘要工具 - 首页脚本

document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const textInput = document.getElementById('textInput');
    const fileInput = document.getElementById('fileInput');
    const summaryRatio = document.getElementById('summaryRatio');
    const ratioValue = document.getElementById('ratioValue');
    const generateBtn = document.getElementById('generateBtn');
    const clearBtn = document.getElementById('clearBtn');
    const copyBtn = document.getElementById('copyBtn');
    const saveBtn = document.getElementById('saveBtn');
    const summaryTab = document.getElementById('summaryTab');
    const keywordsTab = document.getElementById('keywordsTab');
    const originalTab = document.getElementById('originalTab');
    const summaryContent = document.getElementById('summaryContent');
    const keywordsContent = document.getElementById('keywordsContent');
    const originalContent = document.getElementById('originalContent');
    const loadingSpinner = document.getElementById('loadingSpinner');
    const alertContainer = document.getElementById('alertContainer');

    // 初始化工具提示
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // 更新比例值显示
    summaryRatio.addEventListener('input', function() {
        ratioValue.textContent = `${this.value}%`;
    });

    // 清空按钮点击事件
    clearBtn.addEventListener('click', function() {
        textInput.value = '';
        fileInput.value = '';
        summaryContent.textContent = '';
        keywordsContent.textContent = '';
        originalContent.textContent = '';
        updateButtonStates();
    });

    // 复制按钮点击事件
    copyBtn.addEventListener('click', function() {
        const textToCopy = summaryContent.textContent;
        if (textToCopy) {
            navigator.clipboard.writeText(textToCopy).then(function() {
                showAlert('success', '复制成功！');
            }).catch(function(err) {
                showAlert('danger', '复制失败：' + err);
            });
        }
    });

    // 保存按钮点击事件
    saveBtn.addEventListener('click', function() {
        const summary = summaryContent.textContent;
        const keywords = keywordsContent.textContent.split('、');
        const original = originalContent.textContent;
        const ratio = parseFloat(summaryRatio.value) / 100;

        if (summary && original) {
            const historyItem = {
                '摘要': summary,
                '关键词': keywords,
                '原文': original,
                '比例': ratio,
                '日期': new Date().toISOString(),
                '来源': '文本'
            };

            fetch('/api/history', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(historyItem)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showAlert('success', '保存成功！');
                } else {
                    throw new Error(data.error || '保存失败');
                }
            })
            .catch(error => {
                showAlert('danger', '保存失败：' + error.message);
            });
        }
    });

    // 生成摘要按钮点击事件
    generateBtn.addEventListener('click', function() {
        const text = textInput.value.trim();
        const ratio = parseFloat(summaryRatio.value) / 100;

        if (!text) {
            showAlert('warning', '请输入文本内容！');
            return;
        }

        // 显示加载动画
        loadingSpinner.classList.remove('d-none');
        generateBtn.disabled = true;

        // 发送请求
        fetch('/api/summarize', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                text: text,
                ratio: ratio
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                throw new Error(data.error);
            }

            // 更新内容
            summaryContent.textContent = data.summary;
            keywordsContent.textContent = data.keywords.join('、');
            originalContent.textContent = data.original;

            // 更新按钮状态
            updateButtonStates();

            showAlert('success', '摘要生成成功！');
        })
        .catch(error => {
            showAlert('danger', '生成失败：' + error.message);
        })
        .finally(() => {
            // 隐藏加载动画
            loadingSpinner.classList.add('d-none');
            generateBtn.disabled = false;
        });
    });

    // 文件上传处理
    fileInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (!file) return;

        // 检查文件大小
        const maxSize = 10 * 1024 * 1024; // 10MB
        if (file.size > maxSize) {
            showAlert('warning', '文件大小超过限制（10MB）！');
            fileInput.value = '';
            return;
        }

        // 检查文件类型
        const allowedTypes = ['text/plain', 'application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/markdown', 'text/html'];
        if (!allowedTypes.includes(file.type)) {
            showAlert('warning', '不支持的文件格式！');
            fileInput.value = '';
            return;
        }

        // 创建FormData对象
        const formData = new FormData();
        formData.append('file', file);

        // 显示加载动画
        loadingSpinner.classList.remove('d-none');

        // 上传文件
        fetch('/api/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                throw new Error(data.error);
            }

            // 更新文本输入框
            textInput.value = data.text;
            updateButtonStates();
        })
        .catch(error => {
            showAlert('danger', '文件上传失败：' + error.message);
        })
        .finally(() => {
            // 隐藏加载动画
            loadingSpinner.classList.add('d-none');
        });
    });

    // 更新按钮状态
    function updateButtonStates() {
        const hasText = textInput.value.trim().length > 0;
        const hasSummary = summaryContent.textContent.trim().length > 0;

        generateBtn.disabled = !hasText;
        clearBtn.disabled = !hasText && !hasSummary;
        copyBtn.disabled = !hasSummary;
        saveBtn.disabled = !hasSummary;
    }

    // 显示提示信息
    function showAlert(type, message) {
        const alert = document.createElement('div');
        alert.className = `alert alert-${type} alert-dismissible fade show`;
        alert.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        `;

        alertContainer.appendChild(alert);

        // 3秒后自动关闭
        setTimeout(() => {
            alert.classList.remove('show');
            setTimeout(() => alert.remove(), 150);
        }, 3000);
    }

    // 初始化按钮状态
    updateButtonStates();
});